package de.bbl.android.adapter.NewsCenter;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import de.bbl.android.BBLAndroidFragmentActivity;
import de.bbl.android.R;
import de.bbl.android.activities.NewsExpandedActivity;
import de.bbl.android.classes.RssItem;
import de.bbl.android.tools.Tools;

public class NewsArrayAdapter extends ArrayAdapter<RssItem>{

	private final Activity context;
	private final RssItem[] values;
	private boolean finished = false; 

	static class ViewHolder {
		public ImageView Image;
		public TextView date;
		public TextView title;
	}
	
	public NewsArrayAdapter(Activity context, RssItem[] values) {
		super(context, R.layout.row_layout_news, android.R.id.text1, values);
		this.context = context;
		this.values = values;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		View rowView = convertView;
		
		if (rowView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			rowView = inflater.inflate(R.layout.row_layout_news, null);
			ViewHolder viewHolder = new ViewHolder();
			viewHolder.date = (TextView) rowView.findViewById(R.id.textview_news1);
			viewHolder.title = (TextView) rowView.findViewById(R.id.textview_news2);
			viewHolder.Image = (ImageView) rowView.findViewById(R.id.imageView_news1);
			rowView.setTag(viewHolder);
		}

		ViewHolder holder = (ViewHolder) rowView.getTag();

		holder.title.setText(values[position].getTitle());
		holder.date.setText(values[position].getShortDateString());

		String[] filename = values[position].getImagePath();
		
		int width = 100;
		int height = width;
		
		if (filename[0] != null) {
			try {
				if (values[position].getFirstBitmap() != null) {
					drawImage(values[position].getFirstBitmap(), holder.Image, width, height); 
				} else {
					drawImage(BitmapFactory.decodeResource(Resources.getSystem(), android.R.drawable.ic_delete), holder.Image, width, height);
					LoadAndRepresentImage(filename, holder.Image, width, height, values[position]);
				}
				/*
				Bitmap bm = BitmapFactory.decodeFile(filename[0]);
				holder.Image.setMaxHeight(holder.title.getHeight());
				holder.Image.setMaxWidth(holder.title.getHeight());
				holder.Image.setImageBitmap(getResizedBitmap(bm, height, width));
				*/
			} catch (Exception e ) {
				Tools.AppendToErrorFile(e.getMessage());
				// e.printStackTrace();
			}
			/*
			holder.Image.setMaxHeight(holder.Title.getHeight());
			holder.Image.setMaxWidth(holder.Title.getHeight());
			holder.Image.setImageBitmap(BitmapFactory.decodeFile(filename[0]));
			holder.Title.setCompoundDrawablesWithIntrinsicBounds(holder.Image.getDrawable(), null, null, null);
			*/
		} else {
			holder.Image.setMaxHeight(holder.title.getHeight());
			holder.Image.setMaxWidth(holder.title.getHeight());
			Bitmap bm = BitmapFactory.decodeResource(Resources.getSystem(), android.R.drawable.ic_delete);
			holder.Image.setImageBitmap(getResizedBitmap(bm, height, width));
			/*
			holder.Image.setMaxHeight(holder.Title.getHeight());
			holder.Image.setMaxWidth(holder.Title.getHeight());
			holder.Image.setImageResource(android.R.drawable.ic_delete);
			*/
			// holder.Title.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_delete, null, null, null);
		}
		return rowView;
	}
	
	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// CREATE A MATRIX FOR THE MANIPULATION
		Matrix matrix = new Matrix();
		// RESIZE THE BIT MAP
		matrix.postScale(scaleWidth, scaleHeight);
		// RECREATE THE NEW BITMAP
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
		return resizedBitmap;
	}
	
	public Bitmap LoadImageFromWebOperations(String url) {
        try
        {
        	// String tempUrl = url.substring(0,url.lastIndexOf("/") - 1).substring(url.lastIndexOf("/")) + "_" + url.substring(url.lastIndexOf("/"));
        	String tempUrl = url.substring(0,url.lastIndexOf("/") -1);
        	tempUrl = tempUrl.substring(tempUrl.lastIndexOf("/") + 1) + "_" + url.substring(url.lastIndexOf("/") + 1); 
        	String filename = BBLAndroidFragmentActivity.bbl_temp_img_sd_path + tempUrl;
        	File file = new File(filename);
        	if (file.exists()) {
                return BitmapFactory.decodeFile(file.getPath());
        	}
        	
        	InputStream is = (InputStream) new URL(url).getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
        	
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
            return BitmapFactory.decodeFile(file.getPath());
        }catch (Exception e) {
        	Tools.AppendToErrorFile(e.getMessage());
            // e.printStackTrace();
            return null;
        }
    }

	private void LoadAndRepresentImage(final String[] filename, final ImageView imageView, final int width, final int height, final RssItem currentItem) {
    	final Handler refresh = new Handler(Looper.getMainLooper());
    	Runnable runnable = new Runnable() {			
			public void run() {
				// drawImage(BitmapFactory.decodeResource(Resources.getSystem(), android.R.drawable.ic_delete), imageView, width, height);
				setFinished(false);
				
				for (int i = 0; i < filename.length; i++) {
					LoadImageFromWebOperations(filename[i]);
				}
				
				currentItem.setFirstBitmap(LoadImageFromWebOperations(filename[0]));
				
				final Bitmap bm = currentItem.getFirstBitmap();
		    	refresh.post(new Runnable() {
					public void run() {
						drawImage(bm, imageView, width, height);
						setFinished(true);
					}
				});				
			}
		};		
		new Thread(runnable).start();

	}

	private void drawImage(Bitmap bm, final ImageView imageView, final int width, final int height) {
		imageView.setMaxHeight(height);
		imageView.setMaxWidth(width);
		imageView.setImageBitmap(getResizedBitmap(bm, height, width));
	}

	public void SetItemView(AdapterView<?> parent, View view, int position, long id) {
		RssItem feed = values[position];
        Intent itemintent = new Intent(context,NewsExpandedActivity.class);
        
        Bundle b = new Bundle();
        b.putString("title", feed.getTitle());
        b.putString("description", feed.getDescription());
        b.putString("link", feed.getLink());
        b.putString("pubdate", feed.getDate());
        b.putStringArray("pics", feed.getImagePath());
        
        itemintent.putExtra("android.intent.extra.INTENT", b);
        
        context.startActivity(itemintent);
	}

	public boolean isFinished() {
		return finished;
	}
	
	public void setFinished(boolean finished) {
		this.finished = finished;
	}
}
